package com.zpkj.portal.interceptor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zpkj.portal.utils.JsonUtils;

import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

/**
 * 日志拦截器
 * @author admin
 *
 */
@Component
public class LogInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		//解决angular跨越 begin
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Headers","application/json");
		//解决angular跨越 end

		String ip = request.getRemoteAddr();
		String agent = request.getHeader("User-Agent");
		String osName = "未知";
		if(StringUtils.isNotEmpty(agent)){
			UserAgent userAgent = UserAgent.parseUserAgentString(agent);
			OperatingSystem os = userAgent.getOperatingSystem();
			osName = os.getName();
			if(StringUtils.isEmpty(osName) || osName.toLowerCase().equals("unknown")){
				agent = agent.toLowerCase();
				if(agent.indexOf("ios") >= 0 || agent.indexOf("iphone") >= 0 || agent.indexOf("mac") >= 0 || agent.indexOf("ipad") >= 0 || agent.indexOf("ipod") >= 0){
					osName = "IOS";
				}else if(agent.indexOf("android") >= 0){
					osName = "Android";
				}
			}
		}
		String methodName = "";
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			methodName = handlerMethod.getBeanType().getSimpleName() + "." + handlerMethod.getMethod().getName();
		}
//		String result = request.getParameterMap() == null ? "" : new Gson().toJson(request.getParameterMap());
		logger.info("请求方法:【{}】 IP:{} 终端:{} Header:{}", methodName, ip, osName, JsonUtils.toJson(getHeaderMap(request)));
		return true;
	}

	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 将客户端header信息封装成map
	 * 
	 * @param request
	 * @return
	 */
	public static Map<Object, Object> getHeaderMap(HttpServletRequest request) {
		Enumeration<?> headers = request.getHeaderNames();
		Map<Object, Object> headerMap = new HashMap<Object, Object>();
		while (headers.hasMoreElements()) {
			Object key = headers.nextElement();
			if (key != null) {
				String tmpKey = key.toString();
				String value = request.getHeader(tmpKey);
				tmpKey = tmpKey.toLowerCase().replace('-', '_');
				headerMap.put(tmpKey, value);
			}
		}
		return headerMap;
	}

}